<template>
  <view class="container">
    <view class="header">
      <button class="add-btn" @click="toAddPage"><uni-icons 
            type="plusempty" 
            size="25" 
            color="#000000" 
          ></uni-icons></button>
    </view>
    
    <view class="search-box">
      <uni-search-bar 
        placeholder="搜索笔记" 
        v-model="searchText" 
        @confirm="searchNotes"
      />
    </view>
    
    <!-- 加载状态 -->
    <view class="loading" v-if="loading">
      <text>加载笔记中...</text>
    </view>
    
    <!-- 空状态 -->
    <view class="empty" v-else-if="notes.length === 0">
      <image src="/static/logo.png" class="empty-img" />
	  <view>
		<text class="empty-text">暂无笔记</text>
	  </view>
      <button class="empty-btn" @click="toAddPage">创建新笔记</button>
    </view>
    
    <!-- 笔记列表 -->
    <view class="note-list" v-else>
		
      <view class="note-card" v-for="note in filteredNotes" :key="note._id" >
		  
        <view class="note-header" @click="toDetailPage(note._id)">
			<view style="width: 560rpx;">
				<text class="note-title">{{ note.title || '无标题' }}</text>
			</view>
			<view style="width: 25%;">
				<text class="note-date">{{ formatDate(note.updated_at) }}</text>
			</view>
        </view>
		
        <text class="note-content" @click="toDetailPage(note._id)">{{ note.truncatedContent }}</text>
		
        <view class="note-footer">
          <uni-icons type="compose" size="25" color="#999" @click.stop="toEditPage(note._id)"></uni-icons>
          <uni-icons type="trash" size="25" color="#ff5050" @click.stop="deleteNote(note._id)"></uni-icons>
        </view>
		
      </view>
    </view>

  </view>
</template>

<script>
export default {
	
  data() {
    return {
      notes: [],
      searchText: '',
      loading: true // 添加加载状态
    };
  },
  computed: {
    filteredNotes() {
      return this.notes.map(note => ({
        ...note,
        truncatedContent: note.content?.length > 21 
          ? note.content.substring(0, 19) + '...' 
          : note.content
      }));
    }
  },
  onShow() {
    this.getNoteList();
  },
  filters: {
    truncate(value, length) {
      if (!value) return '';
      return value.length > length ? value.substring(0, length) + '...' : value;
    }
  },
  methods: {
    async getNoteList() {
      this.loading = true;
      try {
        const res = await uniCloud.callFunction({
          name: 'note',
          data: { action: 'getList' }
        });
        
        console.log('云函数响应:', res);
        
        if (res.result.code === 200) {
          console.log('获取到的笔记数据:', res.result.data);
          this.notes = res.result.data || [];
        } else {
          console.error('获取笔记失败:', res.result);
          uni.showToast({ 
            title: `加载失败: ${res.result.message || '未知错误'}`,
            icon: 'none'
          });
        }
      } catch (e) {
        console.error('调用云函数异常:', e);
        uni.showToast({ 
          title: '网络请求异常',
          icon: 'none'
        });
      } finally {
        this.loading = false;
        uni.hideLoading();
      }
    },
    
    async deleteNote(id) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该笔记吗？',
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading({ title: '删除中' });
            try {
              const result = await uniCloud.callFunction({
                name: 'note',
                data: { action: 'delete', params: { id } }
              });
              
              if (result.result.code === 200) {
                uni.showToast({ title: '删除成功' });
                // 从本地列表中移除
                this.notes = this.notes.filter(note => note._id !== id);
              } else {
                uni.showToast({ 
                  title: `删除失败: ${result.result.message || '未知错误'}`,
                  icon: 'none'
                });
              }
            } catch (e) {
              console.error('删除笔记异常:', e);
              uni.showToast({ 
                title: '删除操作异常',
                icon: 'none'
              });
            } finally {
              uni.hideLoading();
            }
          }
        }
      });
    },
    
    toAddPage() {
      uni.navigateTo({ url: '/pages/add/add'});
    },
    
    toEditPage(id) {
      uni.navigateTo({ url: `/pages/edit/edit?id=${id}` });
    },
    
    toDetailPage(id) {
      uni.navigateTo({ url: `/pages/detail/detail?id=${id}` });
    },
    
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    
    searchNotes() {
      // 搜索逻辑在计算属性中处理
    }
  }
};
</script>

<style scoped>
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;
  font-size: 32rpx;
  color: #8B7D6B; /* 改为复古黄褐色 */
}
	
.container {
  padding: 20rpx;
  background-color: #F5F0E6; /* 改为米黄色纸张底色 */
  min-height: 100vh;
}

.add-btn {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	background-color: #D4B483; /* 改为牛皮纸按钮色 */
	border-color: #D4B483;
	border: #D4B483;
	color: #5C4A36; /* 深棕色图标 */
	display: flex;
	justify-content: center;
    align-items: center;
}

.search-box {
  margin-bottom: 20rpx;
}

.empty {
	text-align: center;
	margin-top: 50rpx;
	height: auto;
}

.empty-img {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #8B7D6B; /* 复古文字色 */
  margin: 30rpx 0;
  
}

.empty-btn {
  background-color: #A38F6B; /* 复古按钮色 */
  color: #FFF;
  width: 60%;
  margin-top: 60rpx;
}

.note-card {
  background-color: #FFFDF5; /* 改为轻微泛黄的白色 */
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(139, 125, 107, 0.1); /* 改为黄褐色阴影 */
  border: 1rpx solid #E0D5C8; /* 添加纸张边缘线 */
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.note-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #5C4A36; /* 深棕色标题 */
}

.note-date {
  font-size: 26rpx;
  color: #8B7D6B; /* 复古日期色 */
}

.note-content {
  font-size: 32rpx;
  color: #6E5C4B; /* 中等棕色正文 */
  line-height: 1.6;
  margin-bottom: 25rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.note-footer {
  display: flex;
  justify-content: flex-end;
  border-top: 1rpx solid #D4C9B8; /* 改为复古分割线 */
  padding-top: 20rpx;
}

.note-footer uni-icons {
  margin-left: 30rpx;
}
.note-footer uni-icons[type="compose"] {
  color: #8B7D6B; /* 编辑图标改为复古色 */
}
.note-footer uni-icons[type="trash"] {
  color: #C17C74; /* 删除按钮改为暗红色 */
}
</style>